﻿using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json.Linq;

[ApiController]
[Route("api/[controller]/[action]")]
public class LoginController : ControllerBase
{
    private readonly IConfiguration _configuration;
    private readonly JwtHelper _jwtHelper;
    private readonly HttpClient _httpClient;
    private readonly RedisService _redisService;

    public LoginController(IConfiguration configuration, JwtHelper jwtHelper, RedisService redisService)
    {
        _configuration = configuration;
        _jwtHelper = jwtHelper;
        _httpClient = new HttpClient();
        _redisService = redisService;
    }

    /// <summary>
    /// 处理微信登录
    /// </summary>
    /// <param name="code">前端传入的微信授权码</param>
    /// <returns>返回 JWT 令牌</returns>
    [HttpGet("wx-login")]
    public async Task<IActionResult> WxLogin([FromQuery] string code)
    {
        if (string.IsNullOrEmpty(code))
        {
            return BadRequest("Invalid code");
        }

        string appId = _configuration["WeChat:AppId"];
        string appSecret = _configuration["WeChat:AppSecret"];

        // 使用授权码换取 access_token 和 openid
        string wxUrl = $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={appId}&secret={appSecret}&code={code}&grant_type=authorization_code";

        var response = await _httpClient.GetStringAsync(wxUrl);
        var wxData = JObject.Parse(response);

        if (wxData["openid"] == null)
        {
            return BadRequest("Invalid WeChat response");
        }

        string openid = wxData["openid"].ToString(); // 获取微信用户的 OpenID

        // 生成 JWT 令牌
        string token = _jwtHelper.GenerateToken(openid);

        return Ok(new { Token = token });
    }

    /// <summary>
    /// 退出登录，加入 JWT 黑名单
    /// </summary>
    /// <returns></returns>
    [Authorize]
    [HttpPost("logout")]
    public async Task<IActionResult> Logout()
    {
        var token = Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
        if (string.IsNullOrEmpty(token))
        {
            return BadRequest("Token 不存在");
        }

        int expireMinutes = int.Parse(_configuration["Redis:ExpireMinutes"]);
        await _redisService.AddTokenToBlacklist(token, expireMinutes);

        return Ok("退出成功，Token 已作废");
    }

    /// <summary>
    /// 验证jwt有效性
    /// </summary>
    /// <returns></returns>
    [Authorize]
    [HttpGet]
    public IActionResult GetProtectedData()
    {
        var userId = User.Identity.Name; // 获取JWT里的openid
        var claims = User.Claims.Select(c => new { c.Type, c.Value });

        return Ok(new { Message = "Success! You accessed a protected API.", UserId = userId, Claims = claims });
    }
}
